import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls.Material 2.15
import Qt.labs.folderlistmodel 1.0
import "../components" 1.0

Page {
    id: logsPage
    readonly property int cmd_logs_download: 7001 //RMSClient日志下载
    readonly property int cmd_logs_clean: 7002 //RMSClient日志文件清理
    property string robotId: ""
    // 当前标签页索引 (0 = RMSMaster, 1 = RMSClient)
    property int currentTabIndex: 0
    // 保存原始日志内容
    property string originalLogContent: ""
    padding: 15
    
    /**
     * 提示信息管理器
     */
    ToastManager {
        id: toastManager
    }

    Connections {
        target: robotController
        function onRobotStatus(state) {
            // 显示警告信息
            toastManager.show(state);
        }
    }

    // 添加右键上下文菜单
    Menu {
        id: contextMenu
        property string fileURL
        property string fileName
        property var listViewId
        property var modelId

        MenuItem {
            text: "删除此日志文件"
            onTriggered: {
                // 确认删除
                deleteDialog.fileURL = contextMenu.fileURL
                deleteDialog.fileName = contextMenu.fileName
                deleteDialog.modelId = contextMenu.modelId
                deleteDialog.open()
            }
        }

        // 添加分隔线
        MenuSeparator { }

        // 添加清空所有日志文件选项
        MenuItem {
            text: "清空此列表日志文件"
            onTriggered: {
                clearAllDialog.modelId = contextMenu.modelId
                clearAllDialog.open()
            }
        }
        
        // 添加分隔线
        MenuSeparator { }

        // 添加清空所有日志文件选项
        MenuItem {
            text: "清空机器人上日志文件"
            onTriggered: {
                robotController.cleanClientLogFiles(cmd_logs_clean)
            }
        }
    }

    RowLayout {
        anchors.fill: parent
        spacing: 15
        
        // 左侧日志列表区域
        Rectangle {
            Layout.preferredWidth: 300
            Layout.fillHeight: true
            color: "#f5f5f5"
            border.color: "#ddd"
            
            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 15
                
                // 标题和标签页切换
                RowLayout {
                    Layout.fillWidth: true
                    
                    Text {
                        text: "RMSMaster日志"
                        font.pixelSize: 16
                        font.bold: true
                        color: logsPage.currentTabIndex === 0 ? "black" : "#666"
                        MouseArea {
                            anchors.fill: parent
                            onClicked: logsPage.currentTabIndex = 0
                        }
                    }
                    
                    Text {
                        text: "|"
                        font.bold: true
                    }
                    
                    Text {
                        text: "RMSClient日志"
                        font.pixelSize: 16
                        font.bold: true
                        color: logsPage.currentTabIndex === 1 ? "black" : "#666"
                        MouseArea {
                            anchors.fill: parent
                            onClicked: logsPage.currentTabIndex = 1
                        }
                    }
                    
                    Item {
                        Layout.fillWidth: true
                    }
                }
                
                // 标签页内容
                Item {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    
                    // RMSMaster日志列表
                    Item {
                        anchors.fill: parent
                        visible: logsPage.currentTabIndex === 0
                        
                        ListView {
                            id: masterLogsList
                            anchors.fill: parent
                            clip: true

                            model: FolderListModel {
                                id: masterLogsModel
                                folder: "file:///home/robot/workspaces/ros2_qt/data/logs/"
                                nameFilters: ["*.log", "*.txt"]
                                showDotAndDotDot: false
                                sortField: FolderListModel.Time
                                sortReversed: true
                            }
                            Component.onCompleted: {
                                console.log("Master logs folder path:", masterLogsModel.folder)
                            }

                            delegate: Rectangle {
                                width: ListView.view ? ListView.view.width : 300
                                height: 40
                                color: ListView.isCurrentItem ? Material.accentColor : 
                                    (mouseArea.containsMouse ? "#e0e0e0" : "transparent")
                                
                                Text {
                                    anchors.centerIn: parent
                                    text: fileName
                                }
                                
                                MouseArea {
                                    id: mouseArea
                                    anchors.fill: parent
                                    hoverEnabled: true
                                    // 添加对右键的支持
                                    acceptedButtons: Qt.LeftButton | Qt.RightButton

                                    onClicked: {
                                        if (mouse.button == Qt.RightButton) {
                                            // 处理右键点击 - 显示上下文菜单
                                            contextMenu.fileURL = fileURL
                                            contextMenu.fileName = fileName
                                            contextMenu.currentIndex = index
                                            contextMenu.listViewId = masterLogsList
                                            contextMenu.modelId = masterLogsModel
                                            contextMenu.popup()
                                        } else {
                                            // 处理左键点击
                                            masterLogsList.currentIndex = index
                                            // 显示日志内容，使用 fileURL 属性而不是 filePath
                                            var content = loadLogFile(fileURL)
                                            logContentArea.text = content
                                            // 清空过滤器
                                            filterField.text = ""
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    // RMSClient日志列表
                    Item {
                        anchors.fill: parent
                        visible: logsPage.currentTabIndex === 1
                        
                        ListView {
                            id: clientLogsList
                            anchors.fill: parent
                            clip: true
                            
                            model: FolderListModel {
                                id: clientLogsModel
                                //folder: "file://" + Qt.resolvedUrl("../../../data/" + robotId + "/logs/")
                                folder: "file:///home/robot/workspaces/ros2_qt/data/" + robotId + "/logs/"
                                nameFilters: ["*.log", "*.txt"]
                                showDotAndDotDot: false
                                sortField: FolderListModel.Time
                                sortReversed: true
                            }
                            Component.onCompleted: {
                                console.log("Client logs folder path:", clientLogsModel.folder)
                            }
                            
                            delegate: Rectangle {
                                width: ListView.view ? ListView.view.width : 300
                                height: 40
                                color: ListView.isCurrentItem ? Material.accentColor : 
                                    (mouseArea.containsMouse ? "#e0e0e0" : "transparent")
                                
                                Text {
                                    anchors.centerIn: parent
                                    text: fileName
                                }
                                
                                MouseArea {
                                    id: mouseArea
                                    anchors.fill: parent
                                    hoverEnabled: true
                                    // 添加对右键的支持
                                    acceptedButtons: Qt.LeftButton | Qt.RightButton

                                    onClicked: {
                                        if (mouse.button == Qt.RightButton) {
                                            // 处理右键点击 - 显示上下文菜单
                                            contextMenu.fileURL = fileURL
                                            contextMenu.fileName = fileName
                                            contextMenu.currentIndex = index
                                            contextMenu.listViewId = clientLogsList
                                            contextMenu.modelId = clientLogsModel
                                            contextMenu.popup()
                                        } else {
                                            // 处理左键点击
                                            clientLogsList.currentIndex = index
                                            // 显示日志内容，使用 fileURL 属性而不是 filePath
                                            var content = loadLogFile(fileURL)
                                            logContentArea.text = content
                                            // 清空过滤器
                                            filterField.text = ""
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 下载日志按钮
                Button {
                    Layout.fillWidth: true
                    text: "下载RMSClient日志"
                    onClicked: {
                        // 下载RIMClientrim日志
                        robotController.downloadLogFiles(cmd_logs_download)
                    }
                }
            }
        }

        // 右侧日志预览区域
        GroupBox {
            Layout.fillWidth: true
            Layout.fillHeight: true
            title: "日志预览"

            Column {
                anchors.fill: parent
                spacing: 5

                // 搜索和过滤区域
                Row {
                    width: parent.width
                    spacing: 5

                    TextField {
                        id: filterField
                        width: parent.width - clearButton.width - spacing
                        height: 40
                        placeholderText: "输入关键字过滤日志行..."
                        onTextChanged: applyFilter()
                    }

                    Button {
                        id: clearButton
                        text: "清除"
                        height: 30
                        onClicked: {
                            filterField.text = ""
                        }
                    }
                }

                // 日志内容显示区域
                Flickable {
                    id: flickable
                    width: parent.width
                    height: parent.height - filterField.height - spacing
                    clip: true
                    contentWidth: width
                    contentHeight: Math.max(logContentArea.height, height)

                    TextArea {
                        id: logContentArea
                        readOnly: true
                        wrapMode: TextArea.Wrap
                        selectByMouse: true
                        text: "请选择一个日志文件进行查看"

                        width: flickable.width
                        height: implicitHeight
                    }
                }
            }
        }
    }

    // 加载日志文件内容的函数
    function loadLogFile(fileURL) {
        if (fileURL) {
            try {
                // 将 URL 对象转换为字符串并移除 "file://" 前缀
                var filePath = fileURL.toString().replace("file://", "");

                // 使用C++端的文件读取功能
                var content = fileLoader.readFile(filePath);

                // 保存原始内容
                originalLogContent = content;
                return content;
            } catch (e) {
                return "无法读取日志文件: " + e;
            }
        }
        return "";
    }

    // 应用过滤器函数
    function applyFilter() {
        // 如果没有原始内容，直接返回
        if (!originalLogContent || originalLogContent === "请选择一个日志文件进行查看")
            return;

        // 如果过滤关键字为空，恢复原始内容
        if (filterField.text.length === 0) {
            logContentArea.text = originalLogContent;
            return;
        }

        // 根据关键字过滤行
        var lines = originalLogContent.split('\n');
        var filteredLines = [];
        var keyword = filterField.text.toLowerCase();

        for (var i = 0; i < lines.length; i++) {
            // 如果行包含关键字，则保留该行
            if (lines[i].toLowerCase().indexOf(keyword) !== -1) {
                filteredLines.push(lines[i]);
            }
        }

        // 更新显示内容
        logContentArea.text = filteredLines.join('\n');
    }

    // 删除确认对话框
    Dialog {
        id: deleteDialog
        property string fileURL
        property string fileName
        property var modelId

        title: "确认删除"
        standardButtons: Dialog.Ok | Dialog.Cancel
        modal: true
        focus: true

        x: (parent.width - width) / 2
        y: (parent.height - height) / 2

        Text {
            text: "确定要删除日志文件 \"" + deleteDialog.fileName + "\" 吗？此操作不可撤销。"
            wrapMode: Text.Wrap
        }

        onAccepted: {
            // 调用C++端的删除函数
            var result = fileLoader.deleteFile(deleteDialog.fileURL.replace("file://", ""))
            if (result === "success") {
                toastManager.show("文件删除成功")
                // 刷新文件列表
                deleteDialog.modelId.refresh()
            } else {
                toastManager.show("文件删除失败: " + result)
            }
        }
    }

    // 清空所有日志文件确认对话框
    Dialog {
        id: clearAllDialog
        property var modelId

        title: "确认清空"
        standardButtons: Dialog.Ok | Dialog.Cancel
        modal: true
        focus: true

        x: (parent.width - width) / 2
        y: (parent.height - height) / 2

        Text {
            text: "确定要清空当前目录下的所有日志文件吗？此操作不可撤销。"
            wrapMode: Text.Wrap
        }

        onAccepted: {
            // 使用C++端的批量删除功能
            var directoryPath = clearAllDialog.modelId.folder.toString().replace("file://", "")
            var result = fileLoader.deleteAllLogs(directoryPath)

            // 显示操作结果
            toastManager.show(result)

            // 刷新文件列表
            clearAllDialog.modelId.refresh()

        }
    }
}